
package com.jy.framework.sys.controller;


import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jy.framework.annotation.DataFilter;
import com.jy.framework.annotation.RequiresAction;
import com.jy.framework.annotation.SysLog;
import com.jy.framework.exception.MyException;
import com.jy.framework.sys.service.SysConfigService;
import com.jy.framework.utils.PageUtils;
import com.jy.framework.utils.R;
import com.jy.framework.validator.Assert;
import com.jy.framework.validator.ValidatorUtils;
import com.jy.framework.validator.group.AddGroup;
import com.jy.framework.validator.group.UpdateGroup;
import com.jy.framework.sys.entity.SysUserEntity;
import com.jy.framework.sys.service.SysUserRoleService;
import com.jy.framework.sys.service.SysUserService;
import com.jy.framework.sys.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 系统用户
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月31日 上午10:40:10
 */
@Api(tags = "系统用户")
@RequestMapping("/sys/user")
@RestController
@Slf4j
public class SysUserController extends AbstractController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 所有用户列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:user:list")
    @DataFilter(subDept = true, user = true)
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 所有部门分配管理员列表
     */
    @RequestMapping("/allot")
    @RequiresPermissions("sys:user:allot")
    public R allot(@RequestParam Map<String, Object> params) {
        PageUtils page = sysUserService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 修改登录用户密码
     */
    @SysLog("修改密码")
    @RequestMapping("/password")
    public R password(String password, String newPassword) {
        Assert.isBlank(newPassword, "新密码不为能空");

        //原密码
        password = ShiroUtils.sha256(password, getUser().getSalt());
        //新密码
        newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());

        //更新密码
        boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (!flag) {
            return R.error("原密码不正确");
        }

        return R.ok();
    }

    /**
     * 用户信息
     */
    @RequestMapping("/info/{userId}")
    @RequiresPermissions("sys:user:info")
    public R info(@PathVariable("userId") Long userId) {
        SysUserEntity user = null;

        if (userId != null && userId != 0) {
            user = sysUserService.getById(userId);
        } else {
            user = getUser();
        }

        //获取用户所属的角色列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getId());
        user.setRoleIdList(roleIdList);

        return R.ok().put("user", user);
    }

    /**
     * 保存用户
     */
    @SysLog("保存用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    @ApiOperation("保存用户")
    public R save(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);

        sysUserService.saveOrRole(user);

        return R.ok();
    }

    /**
     * 修改用户
     */
    @SysLog("修改用户")
    @RequestMapping("/update")
    @RequiresPermissions("sys:user:update")
    public R update(@RequestBody SysUserEntity user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);

        sysUserService.update(user);

        return R.ok();
    }

    /**
     * 删除用户
     */
    @SysLog("删除用户")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestBody Long[] userIds) {
        if (ArrayUtils.contains(userIds, 1L)) {
            return R.error("系统管理员不能删除");
        }

        if (ArrayUtils.contains(userIds, getUserId())) {
            return R.error("当前用户不能删除");
        }

        sysUserService.removeByIds(Arrays.asList(userIds));

        return R.ok();
    }
    //    @ApiOperation("导出")
    @SysLog("数据导出")
    @GetMapping("exportExcel")
    @RequiresAction("exportExcel")
    public R exportExcel(ModelMap map, HttpServletRequest request,
                         HttpServletResponse response) {
        ExportParams params = new ExportParams("用户excel数据", "1", ExcelType.XSSF);
        params.setFreezeCol(2);
        Wrapper<SysUserEntity> wrapper = new QueryWrapper<>();
//                添加通用条件
        List<SysUserEntity> list = sysUserService.list(wrapper);
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, SysUserEntity.class);
        map.put(NormalExcelConstants.PARAMS, params);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
        return R.ok();
    }
    //    @ApiOperation("模板")
    @GetMapping("template")
    @RequiresAction("importExcel")
    public R template(ModelMap map, HttpServletRequest request,
                      HttpServletResponse response) {

        ExportParams params = new ExportParams("template", "1", ExcelType.XSSF);
        params.setFreezeCol(2);
//                添加通用条件
        List<SysUserEntity> list = new ArrayList<>();
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, SysUserEntity.class);
        map.put(NormalExcelConstants.PARAMS, params);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
        return R.ok();
    }
    @ApiOperation("导入")
    @SysLog("数据导入")
    @PostMapping("importExcel")
    @RequiresAction("importExcel")
    public R importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request,
                         HttpServletResponse response) throws Exception {
        ImportParams params = new ImportParams();
//        params.setNeedVerfiy(true);
        params.setTitleRows(1);
        params.setHeadRows(1);
//        paramsStr.setNeedCheckOrder(true);
//        paramsStr.setKeyIndex(1);
        ExcelImportResult<SysUserEntity> result = ExcelImportUtil.importExcelMore(file.getInputStream(),
                SysUserEntity.class, params);
        log.error("失败条数-" + result.getFailList().size());
        log.error("失败数据-" + result.getFailList());
        List<SysUserEntity> list = result.getList();
        if (CollectionUtils.isEmpty(list)) {
            throw new MyException("请在excel文件中添加对应数据");
        }
        String userPwd = "123456";
        List<Long> roles=new ArrayList<>();

        String sysUserInit = sysConfigService.queryByKey("SYS_USER_INIT");
        if (StrUtil.isNotBlank(sysUserInit)) {
            JSONObject jsonObject = JSON.parseObject(sysUserInit);
            userPwd = (String) jsonObject.get("userPwd");
            String userRoles = (String) jsonObject.get("userRoles");
            String[] split = userRoles.split(",");
            roles = Arrays.stream(split).map((Function<String, Long>) Long::valueOf).collect(Collectors.toList());
        }

//        处理用户信息
        for (SysUserEntity sysUserEntity : list) {
            sysUserEntity.setPassword(userPwd);
            sysUserEntity.setRoleIdList(roles);
            sysUserService.saveOrRole(sysUserEntity);
        }
//        sysUserService.saveBatch(list);
        return R.ok("本次上传了" + list.size() + "条数据！");
    }
    /**
     * 分配管理员
     */
    @SysLog("分配管理员")
    @RequestMapping("/allotManager")
    @RequiresPermissions("sys:user:allotManager")
    public R allotManager(@RequestBody Long[] userIds) {
        SysUserEntity userEntity = getUser();
        if (userEntity.getUserType() > 1) {
            return R.error("无权限操作！");
        }

        sysUserService.allotBatch(userIds);
        return R.ok();
    }
}
